<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', 'menu.list.searchTable']" />
    <a-card class="general-card" :title="$t('menu.list.searchTable')">
      <a-row>
        <a-col :flex="1">
          <a-form :model="formModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="trueName" label="分类名">
                  <a-input v-model="formModel.name" placeholder="请输入分类名" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" label="是否展示">
                  <a-select v-model="formModel.visibility" :options="statusOptions" placeholder="请选择" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary">
              <template #icon>
                <icon-plus />
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
            <a-upload action="/">
              <template #upload-button>
                <a-button>
                  {{ $t('searchTable.operation.import') }}
                </a-button>
              </template>
            </a-upload>
          </a-space>
        </a-col>
        <a-col :span="12" style="display: flex; align-items: center; justify-content: end">
          <a-button>
            <template #icon>
              <icon-download />
            </template>
            {{ $t('searchTable.operation.download') }}
          </a-button>
          <a-tooltip :content="$t('searchTable.actions.refresh')">
            <div class="action-icon" @click="search"><icon-refresh size="18" /></div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('searchTable.actions.density')">
              <div class="action-icon"><icon-line-height size="18" /></div>
            </a-tooltip>
            <template #content>
              <a-doption v-for="item in densityList" :key="item.value" :value="item.value" :class="{ active: item.value === size }">
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
          <a-tooltip :content="$t('searchTable.actions.columnSetting')">
            <a-popover trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
              <div class="action-icon"><icon-settings size="18" /></div>
              <template #content>
                <div id="tableSetting">
                  <div v-for="(item, index) in showColumns" :key="item.dataIndex" class="setting">
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow />
                    </div>
                    <div>
                      <a-checkbox v-model="item.checked" @change="handleChange($event, item as TableColumnData, index)"></a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="cloneColumns as TableColumnData[]"
        :data="renderData"
        :bordered="false"
        :size="size"
        @page-change="onPageChange"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 + (pagination.current - 1) * pagination.pageSize }}
        </template>
        <template #status="{ record }">
          <span v-if="!record.visibility" class="circle"></span>
          <span v-else class="circle pass"></span>
          {{ record.visibility ? '显示' : '隐藏' }}
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleView(record)">
              <template #icon><icon-eye /></template>
              查看
            </a-button>
            <a-button type="text" size="small" @click="handleEdit(record)">
              <template #icon><icon-edit /></template>
              编辑
            </a-button>
            <a-button type="text" size="small" status="danger" @click="handleDelete(record)">
              <template #icon><icon-delete /></template>
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
    
    <!-- 分类详情对话框 -->
    <a-modal
      v-model:visible="detailVisible"
      :title="'分类详情'"
      :footer="false"
      @cancel="detailVisible = false"
      :mask-closable="true"
      modal-class="category-detail-modal"
      :width="700"
    >
      <div class="category-detail-container" v-if="currentDetailCategory">
        <!-- 顶部信息区域 -->
        <div class="category-detail-header">
          <div class="avatar-container">
            <a-avatar :size="80" :style="{ backgroundColor: currentDetailCategory.visibility ? '#00b42a' : '#f53f3f' }">
              {{ currentDetailCategory.trueName ? currentDetailCategory.trueName.substring(0, 1) : 'U' }}
            </a-avatar>
            <div class="status-badge" :class="{ 'active': currentDetailCategory.visibility }">
              {{ currentDetailCategory.visibility ? '已显示' : '已隐藏' }}
            </div>
          </div>
          <div class="basic-info">
            <h2>{{ currentDetailCategory.name}}</h2>
            <div class="info-item">
              <icon-user /> 分类ID: {{ currentDetailCategory.id }}
            </div>
            <div class="info-item">
              <icon-mobile /> {{ currentDetailCategory.sort }}
            </div>
            <div class="info-item">
              <icon-email /> {{ currentDetailCategory.sellerId || '未关联商户' }}
            </div>
          </div>
          <div class="action-buttons">
            <a-button type="outline" status="success" @click="handleEdit(currentDetailCategory)">
              <template #icon><icon-edit /></template>
              编辑
            </a-button>
            <a-button 
              type="outline" 
              :status="currentDetailCategory.visibility ? 'danger' : 'success'"
              @click="handleToggleStatus(currentDetailCategory)"
              style="margin-left: 8px;"
            >
              <template #icon>
                <icon-poweroff v-if="currentDetailCategory.visibility" />
                <icon-play-arrow-fill v-else />
              </template>
              {{ currentDetailCategory.visibility ? '隐藏' : '显示' }}
            </a-button>
          </div>
        </div>
      </div>
    </a-modal>
    
    <!-- 分类编辑对话框 -->
    <a-modal
      v-model:visible="editVisible"
      :title="editForm.id ? '编辑分类' : '新增分类'"
      @ok="handleEditSubmit"
      @cancel="editVisible = false"
    >
      <a-form :model="editForm" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
        <a-form-item field="name" label="分类名">
          <a-input v-model="editForm.name" placeholder="请输入分类名" />
        </a-form-item>
        <a-form-item field="sort" label="排序">
          <a-input v-model="editForm.sort" placeholder="请输入排序权重" />
        </a-form-item>
        <a-form-item field="status" label="是否展示">
          <a-radio-group v-model="editForm.visibility">
            <a-radio :value="true">展示</a-radio>
            <a-radio :value="false">隐藏</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 删除确认对话框 -->
    <a-modal
      v-model:visible="deleteVisible"
      title="确认删除"
      @ok="handleDeleteConfirm"
      @cancel="deleteVisible = false"
      :ok-text="'确认删除'"
      :cancel-text="'取消'"
      :ok-button-props="{ status: 'danger' }"
      modal-class="delete-confirm-modal"
    >
      <div class="delete-confirm-content">
        <div class="delete-icon">
          <icon-exclamation-circle-fill />
        </div>
        <div class="delete-info">
          <h3>您确定要删除该分类吗？</h3>
          <p>删除后数据将无法恢复，请谨慎操作。</p>
          <p v-if="currentCategory" class="category-info">
            <span>分类ID: {{ currentCategory.id }}</span>
            <span>分类名: {{ currentCategory.name }}</span>
          </p>
        </div>
      </div>
    </a-modal>
    
    <!-- 启用/禁用确认对话框 -->
    <a-modal
      v-model:visible="toggleStatusVisible"
      :title="statusAction ? '确认隐藏' : '确认显示'"
      @ok="handleToggleStatusConfirm"
      @cancel="toggleStatusVisible = false"
      :ok-text="statusAction ? '确认隐藏' : '确认显示'"
      :cancel-text="'取消'"
      :ok-button-props="{ status: statusAction ? 'danger' : 'success' }"
      modal-class="status-confirm-modal"
    >
      <div class="status-confirm-content">
        <div class="status-icon" :class="{ 'disable': statusAction }">
          <icon-poweroff v-if="statusAction" />
          <icon-play-arrow-fill v-else />
        </div>
        <div class="status-info">
          <h3>您确定要{{ statusAction ? '隐藏' : '显示' }}该分类吗？</h3>
          <p>{{ statusAction ? '隐藏后该分类将无法登录系统。' : '显示后该分类将恢复正常使用。' }}</p>
          <p v-if="currentCategory" class="category-info">
            <span>分类ID: {{ currentCategory.id }}</span>
            <span>姓名: {{ currentCategory.trueName || '未设置' }}</span>
            <span>当前状态: {{ currentCategory.visibility ? '显示' : '隐藏' }}</span>
          </p>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import useLoading from '@/hooks/loading'
import { 
  queryCategoryPage, 
  getCategoryDetail, 
  updateCategory, 
  toggleCategoryStatus, 
  deleteCategory,
  CategoryRecord, 
  PageQuery, 
  CategoryDetail 
} from '@/api/category'
import { Pagination } from '@/types/global'
import type { SelectOptionData } from '@arco-design/web-vue/es/select/interface'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import type { DescData } from '@arco-design/web-vue/es/descriptions/interface'
import cloneDeep from 'lodash/cloneDeep'
import Sortable from 'sortablejs'
import { 
  IconEdit, 
  IconDelete, 
  IconPoweroff, 
  IconPlayArrowFill, 
  IconEye, 
  IconExclamationCircleFill,
  IconUser,
  IconMobile,
  IconEmail
} from '@arco-design/web-vue/es/icon'
import { Message, Modal } from '@arco-design/web-vue'

type SizeProps = 'mini' | 'small' | 'medium' | 'large'
type Column = TableColumnData & { checked?: true }

const generateFormModel = () => {
  return {
    name: '',
    visibility: ''
  }
}
const { loading, setLoading } = useLoading(true)
const { t } = useI18n()
const renderData = ref<CategoryRecord[]>([])
const formModel = ref(generateFormModel())
const cloneColumns = ref<Column[]>([])
const showColumns = ref<Column[]>([])

// 对话框可见性控制
const detailVisible = ref(false)
const editVisible = ref(false)
const deleteVisible = ref(false)
const toggleStatusVisible = ref(false)

// 当前操作的分类数据
const currentCategory = ref<CategoryRecord | null>(null)
// 当前查看的分类详情
const currentDetailCategory = ref<CategoryDetail | null>(null)
// 状态操作类型：true表示禁用操作，false表示启用操作
const statusAction = ref(false)
const editForm = ref<CategoryDetail>({
  id: 0,
  name: '',           // 分类名称
  sort: 0,            // 排序
  visibility: true,   // 首页是否显示
  sellerId: 0         // 商家ID
})

// 分类详情数据
const detailData = ref<DescData[]>([])

const size = ref<SizeProps>('medium')

const basePagination: Pagination = {
  current: 1,
  pageSize: 3,
}
const pagination = reactive({
  ...basePagination,
})
const densityList = computed(() => [
  {
    name: t('searchTable.size.mini'),
    value: 'mini',
  },
  {
    name: t('searchTable.size.small'),
    value: 'small',
  },
  {
    name: t('searchTable.size.medium'),
    value: 'medium',
  },
  {
    name: t('searchTable.size.large'),
    value: 'large',
  },
])
const columns = computed<TableColumnData[]>(() => [
  {
    title: t('searchTable.columns.index'),
    dataIndex: 'index',
    slotName: 'index',
  },
  {
    title: '分类ID',
    dataIndex: 'id',
  },
  {
    title: '分类名',
    dataIndex: 'name',
  },
  {
    title: '排序',
    dataIndex: 'sort',
  },
  {
    title: '可见状态',
    dataIndex: 'visibility',
    slotName: 'status',
  },
  {
    title: t('searchTable.columns.operations'),
    dataIndex: 'operations',
    slotName: 'operations',
  },
])

const statusOptions = computed<SelectOptionData[]>(() => [
  {
    label: '显示',
    value: true,
  },
  {
    label: '隐藏',
    value: false,
  },
])
// 查看分类详情
const handleView = async (record: CategoryRecord) => {
  setLoading(true)
  try {
    const response = await getCategoryDetail(record.id)
    currentDetailCategory.value = response.data

    // 构建详情数据 (保留这部分以防需要)
    detailData.value = [
      { label: '分类ID', value: record.id },
      { label: '分类名称', value: record.name || '未设置' },
      { label: '排序', value: record.sort ?? '未设置' },
      { label: '首页显示', value: record.visibility ? '显示' : '隐藏' },
      { label: '商家ID', value: record.sellerId || '未设置' },
    ]

    detailVisible.value = true
  } catch (error) {
    Message.error('获取分类详情失败')
    console.error('获取分类详情失败:', error)
  } finally {
    setLoading(false)
  }
}

// 处理编辑按钮点击
const handleEdit = async (record: CategoryRecord) => {
  setLoading(true)
  try {
    const response = await getCategoryDetail(record.id)
    editForm.value = response.data
    editVisible.value = true
  } catch (error) {
    Message.error('获取分类信息失败')
    console.error('获取分类信息失败:', error)
  } finally {
    setLoading(false)
  }
};

// 提交编辑表单
const handleEditSubmit = async () => {
  setLoading(true)
  try {
    await updateCategory(editForm.value)
    Message.success('保存成功')
    editVisible.value = false
    search() // 刷新列表
  } catch (error) {
    Message.error('保存失败')
    console.error('保存失败:', error)
  } finally {
    setLoading(false)
  }
}

// 处理禁用/启用按钮点击
const handleToggleStatus = (record: CategoryRecord) => {
  currentCategory.value = record
  // 设置操作类型：true表示禁用操作，false表示启用操作
  statusAction.value = record.visibility
  toggleStatusVisible.value = true
};

// 确认禁用/启用
const handleToggleStatusConfirm = async () => {
  if (!currentCategory.value) return

  const action = statusAction.value ? '隐藏' : '显示'

  try {
    await toggleCategoryStatus(currentCategory.value.id)
    Message.success(`${action}成功`)
    toggleStatusVisible.value = false
    search() // 刷新列表
  } catch (error) {
    Message.error(`${action}失败`)
    console.error(`${action}失败:`, error)
  }
};

// 处理删除按钮点击
const handleDelete = (record: CategoryRecord) => {
  currentCategory.value = record
  deleteVisible.value = true
};

// 确认删除
const handleDeleteConfirm = async () => {
  if (!currentCategory.value) return
  
  try {
    await deleteCategory([currentCategory.value.id])
    Message.success('删除成功')
    deleteVisible.value = false
    search() // 刷新列表
  } catch (error) {
    Message.error('删除失败')
    console.error('删除失败:', error)
  }
};

const fetchData = async (params: PageQuery = { current: 1, pageSize: 20 }) => {
  setLoading(true)
  try {
    const response = await queryCategoryPage(params)
    renderData.value = response.list
    pagination.current = params.current
    pagination.total = response.total
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false)
  }
}

const search = () => {
  // 构建查询参数，过滤掉空值
  const params = {
    ...basePagination,
    ...Object.entries(formModel.value).reduce((acc, [key, value]) => {
      if (value !== '' && value !== undefined && value !== null) {
        acc[key] = value;
      }
      return acc;
    }, {} as Record<string, any>)
  };
  
  fetchData(params as PageQuery);
}
const onPageChange = (current: number) => {
  fetchData({ ...basePagination, current })
}

fetchData()
const reset = () => {
  formModel.value = generateFormModel()
}

const handleSelectDensity = (val: string | number | Record<string, any> | undefined, e: Event) => {
  size.value = val as SizeProps
}

const handleChange = (checked: boolean | (string | boolean | number)[], column: Column, index: number) => {
  if (!checked) {
    cloneColumns.value = showColumns.value.filter((item) => item.dataIndex !== column.dataIndex)
  } else {
    cloneColumns.value.splice(index, 0, column)
  }
}

const exchangeArray = <T extends Array<any>>(array: T, beforeIdx: number, newIdx: number, isDeep = false): T => {
  const newArray = isDeep ? cloneDeep(array) : array
  if (beforeIdx > -1 && newIdx > -1) {
    // 先替换后面的，然后拿到替换的结果替换前面的
    newArray.splice(beforeIdx, 1, newArray.splice(newIdx, 1, newArray[beforeIdx]).pop())
  }
  return newArray
}

const popupVisibleChange = (val: boolean) => {
  if (val) {
    nextTick(() => {
      const el = document.getElementById('tableSetting') as HTMLElement
      const sortable = new Sortable(el, {
        onEnd(e: any) {
          const { oldIndex, newIndex } = e
          exchangeArray(cloneColumns.value, oldIndex, newIndex)
          exchangeArray(showColumns.value, oldIndex, newIndex)
        },
      })
    })
  }
}

watch(
  () => columns.value,
  (val) => {
    cloneColumns.value = cloneDeep(val)
    cloneColumns.value.forEach((item, index) => {
      item.checked = true
    })
    showColumns.value = cloneDeep(cloneColumns.value)
  },
  { deep: true, immediate: true }
)
</script>

<script lang="ts">
export default {
  name: 'CategoryTable',
}
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}
:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
.action-icon {
  margin-left: 12px;
  cursor: pointer;
}
.active {
  color: #0960bd;
  background-color: #e3f4fc;
}
.setting {
  display: flex;
  align-items: center;
  width: 200px;
  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}

// 删除确认对话框样式
:deep(.delete-confirm-modal) {
  .arco-modal-header {
    border-bottom: 1px solid #f2f3f5;
    padding-bottom: 12px;
  }
  
  .arco-modal-footer {
    border-top: 1px solid #f2f3f5;
    padding-top: 12px;
  }
}

.delete-confirm-content {
  display: flex;
  padding: 16px 0;
  
  .delete-icon {
    font-size: 48px;
    color: #f53f3f;
    margin-right: 16px;
    display: flex;
    align-items: center;
  }
  
  .delete-info {
    flex: 1;
    
    h3 {
      margin: 0 0 8px 0;
      font-size: 16px;
      color: #1d2129;
    }
    
    p {
      margin: 0 0 8px 0;
      color: #4e5969;
      font-size: 14px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    .category-info {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px dashed #e5e6eb;
      
      span {
        margin-right: 16px;
        font-weight: 500;
      }
    }
  }
}

// 状态样式
.circle {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #f53f3f;
  margin-right: 8px;
  
  &.pass {
    background-color: #00b42a;
  }
}

// 分类详情对话框样式
:deep(.category-detail-modal) {
  .arco-modal-header {
    border-bottom: 1px solid #f2f3f5;
    padding-bottom: 12px;
  }
  
  .arco-tabs-header {
    margin-bottom: 0;
  }
}

.category-detail-container {
  .category-detail-header {
    display: flex;
    align-items: center;
    padding-bottom: 16px;
    
    .avatar-container {
      position: relative;
      margin-right: 20px;
      
      .status-badge {
        position: absolute;
        bottom: -8px;
        left: 50%;
        transform: translateX(-50%);
        padding: 2px 12px;
        border-radius: 10px;
        font-size: 12px;
        background-color: #f53f3f;
        color: white;
        white-space: nowrap;
        min-width: 60px;
        text-align: center;
        
        &.active {
          background-color: #00b42a;
        }
      }
    }
    
    .basic-info {
      flex: 1;
      
      h2 {
        margin: 0 0 8px 0;
        font-size: 18px;
        color: #1d2129;
      }
      
      .info-item {
        margin-bottom: 6px;
        color: #4e5969;
        font-size: 14px;
        display: flex;
        align-items: center;
        
        .arco-icon {
          margin-right: 6px;
          font-size: 16px;
        }
      }
    }
    
    .action-buttons {
      margin-left: 20px;
    }
  }
  
  .detail-section {
    padding: 16px 0;
    
    .detail-row {
      display: flex;
      margin-bottom: 16px;
      
      .detail-item {
        flex: 1;
        margin-right: 16px;
        
        &.full-width {
          flex: 0 0 100%;
          margin-right: 0;
        }
        
        .detail-label {
          font-size: 13px;
          color: #86909c;
          margin-bottom: 4px;
        }
        
        .detail-value {
          font-size: 14px;
          color: #1d2129;
          word-break: break-word;
        }
      }
    }
  }
}

// 启用/禁用确认对话框样式
:deep(.status-confirm-modal) {
  .arco-modal-header {
    border-bottom: 1px solid #f2f3f5;
    padding-bottom: 12px;
  }
  
  .arco-modal-footer {
    border-top: 1px solid #f2f3f5;
    padding-top: 12px;
  }
}

.status-confirm-content {
  display: flex;
  padding: 16px 0;
  
  .status-icon {
    font-size: 48px;
    color: #00b42a;
    margin-right: 16px;
    display: flex;
    align-items: center;
    
    &.disable {
      color: #f53f3f;
    }
  }
  
  .status-info {
    flex: 1;
    
    h3 {
      margin: 0 0 8px 0;
      font-size: 16px;
      color: #1d2129;
    }
    
    p {
      margin: 0 0 8px 0;
      color: #4e5969;
      font-size: 14px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    .category-info {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px dashed #e5e6eb;
      
      span {
        margin-right: 16px;
        font-weight: 500;
      }
    }
  }
}
</style>


